﻿Public Class UIFPSCounter

    Public Fps As Single = 0

    Public SampleSpan As TimeSpan = TimeSpan.FromSeconds(1)
    Private stopwatch As Stopwatch
    Private sampleFrames As Integer = 0
    Private OutputString As String = ""

    Public Font As SpriteFont
    Public Background As Texture2D

    Public Sub New(UserInterface As UserInterface)
        Font = UserInterface.TextureManager.GetTexture("Default").Font
        Background = UserInterface.TextureManager.GetTexture("Default").Texture2D
    End Sub

    Public Property Enabled As Boolean
        Set(Value As Boolean)
            Select Case Value
                Case True
                    stopwatch = stopwatch.StartNew()
                    _Enabled = True
                Case False
                    stopwatch.Stop()
                    _Enabled = False
            End Select
        End Set
        Get
            Return _Enabled
        End Get
    End Property
    Private _Enabled As Boolean = False

    Public Sub Update()
        If stopwatch.Elapsed > SampleSpan Then
            Fps = CSng(sampleFrames) / CSng(stopwatch.Elapsed.TotalSeconds)
            stopwatch.Reset()
            stopwatch.Start()
            sampleFrames = 0
            OutputString = "FPS: " & Fps.ToString.Substring(0, 5)
        End If
    End Sub

    Public Sub Draw(SpriteBatch As SpriteBatch)
        sampleFrames += 1
        Dim size As Vector2 = Font.MeasureString("X")
        Dim rc As New Rectangle(0, 0, CInt(size.X * 14.0F), CInt(size.Y * 1.3F))
        Dim layout As New Layout(SpriteBatch.GraphicsDevice.Viewport)
        rc = layout.Place(rc, 0.01F, 0.01F, Alignment.TopLeft)
        size = Font.MeasureString(OutputString)
        layout.ClientArea = rc
        Dim pos As Vector2 = layout.Place(size, 0, 0.1F, Alignment.Center)
        SpriteBatch.Draw(Background, rc, New Color(0, 0, 0, 128))
        SpriteBatch.DrawString(Font, OutputString, pos, Color.White)
    End Sub

End Class
